// pages/organization/list/list.js
const API = require('../../../utils/api')
const pathUrl = require('../../../utils/common.js'); 
Page({
  data: {
    userInfo:{},
    triggered:false,
    searchKeyword: '',
    pageNum: 1, // 当前页码
    pageSize: 5, // 每页显示数量
    hasMore: false, // 是否还有更多数据
    organizations: [],
    showModal: false,//二维码弹出框
    base64:''
  },

  onLoad() {
    const app = getApp();
    this.setData({
      userInfo:app.globalData.userInfo
    })
  },
  onShow(){
    this.loadOrganizations()
  },
  onRefresh(){
    this.setData({
      pageNum:1,
      hasMore:false
    })
    this.loadOrganizations()
    this.setData({
      triggered:false
    })
  },
 async onReachBottom(){
    if (!this.data.hasMore){
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none'
      });
      return;
    }
    let tempList = this.data.organizations;
    this.setData({
      pageNum:this.data.pageNum+1,
    })
   await this.loadOrganizations()
    this.setData({
      organizations:[...tempList,...this.data.organizations]
    })
  },
  async loadOrganizations() {
    wx.showLoading({
      title: '搜索中...',
      mask: true
    });
    let res = await API.orgUserList({pageSize:this.data.pageSize,pageNum:this.data.pageNum,orgName:this.data.searchKeyword})
    if(res.records){
      for(let i=0;i<res.records.length;i++){
        res.records[i].avatar = pathUrl+res.records[i].avatar
      }
    }
    this.setData({
      organizations:res.records,
      hasMore:res.pages>this.data.pageNum?true:false,
    })
    wx.hideLoading();
  },

  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value,
      pageNum:1
    })
    this.loadOrganizations()
  },

  clearSearch() {
    this.setData({ searchKeyword: '',pageNum:1 })
  },
  showQuitConfirm(e) {
    let id = e.currentTarget.dataset.id
    //let that = this;
    wx.showModal({
      title: '确认退出',
      content: '确定要退出该组织吗？退出后将无法访问组织内容',
      confirmText: '确认退出',
      confirmColor: '#ff4d4f',
      success: async (res) => {
        if (res.confirm) {
          await API.orgDelete(id)
          this.loadOrganizations()
        }else{
        }
      }
    })
  },

  navigateToCreate(){
    wx.navigateTo({
      url: '/pages/org/add/add',
    })
  },
    //展示二维码
  async showQrCode(e){
    let id = e.currentTarget.dataset.id
    this.setData({
      showModal:true
    })
    let base64Res = await API.orgJsonQr(id)
    console.log('base64',base64Res)
    this.setData({
      base64:base64Res
    })
  },
  // 隐藏弹窗
  hideModal() {
    this.setData({ 
      showModal: false ,
      base64:''
    });
  },
  // 阻止弹窗内容点击事件冒泡
  stopPropagation() {},
})